using System.Collections.Generic;
using Voodoo.Sauce.Internal.VoodooTune;
using Voodoo.Tune.Core;

namespace Voodoo.Sauce.Debugger
{
	public class VoodooTuneAbTestsDebugScreen : Screen
	{
		private Dictionary<Cohort, DebugRadioButton> _radioButtons = new Dictionary<Cohort, DebugRadioButton>();

		public override void OnScreenShow()
		{
			if (DebugVTManager.DraftDebugConfiguration == null)
			{
				DebugVTManager.NewDebugDraftConfiguration();
			}
			foreach (KeyValuePair<Cohort, DebugRadioButton> kvp in _radioButtons)
			{
				kvp.Value.SetValue(DebugVTManager.DraftDebugConfiguration.SelectedCohorts.Exists((Cohort x) => x.Id == kvp.Key.Id));
			}
		}

		private void Start()
		{
			CreateAbTestsSections();
		}

		private void CreateAbTestsSections()
		{
			IEnumerable<ABTest> debugAbTests = DebugVTManager.GetDebugAbTests();
			DebugVTConfiguration debugVTConfiguration = (DebugVTManager.IsDraftDebugConfiguration ? DebugVTManager.DraftDebugConfiguration : DebugVTManager.CurrentDebugConfiguration);
			Button("None", OnNoneButtonClicked);
			foreach (ABTest item in debugAbTests)
			{
				Label(item.Name);
				CreateRadioGroup();
				foreach (Cohort cohort in item.Cohorts)
				{
					ABTest tempAbTest = item;
					Cohort tempCohort = cohort;
					DebugRadioButton debugRadioButton = RadioButton(cohort.Name, delegate(bool value)
					{
						SelectCohort(value, tempAbTest, tempCohort);
					});
					debugRadioButton.SetValue(debugVTConfiguration.SelectedCohorts.Exists((Cohort x) => x.Id == cohort.Id));
					_radioButtons.Add(cohort, debugRadioButton);
				}
				CloseRadioGroup();
			}
		}

		private void OnNoneButtonClicked()
		{
			CheckConfiguration(force: true);
		}

		private void SelectCohort(bool value, ABTest abTest, Cohort cohort)
		{
			if (value)
			{
				DebugVTManager.AddCohort(cohort, abTest);
			}
			else if (DebugVTManager.RemoveCohort(cohort, abTest))
			{
				CheckConfiguration();
			}
		}

		private void CheckConfiguration(bool force = false)
		{
			DebugVTConfiguration draftDebugConfiguration = DebugVTManager.DraftDebugConfiguration;
			if (force || (draftDebugConfiguration != null && draftDebugConfiguration.HasNoneSelected))
			{
				DebugVTManager.ResetDebugDraftConfiguration();
				ResetRadioGroups(callCallback: false);
			}
		}
	}
}
